package cn.dnui_xqh414.dnuifood_16110100414;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import cn.dnui_xqh414.dnuifood_16110100414.bean.ResultBean;
import cn.dnui_xqh414.dnuifood_16110100414.bean.UserInfo;
import cn.dnui_xqh414.dnuifood_16110100414.listener.OnRetrofitListener;
import cn.dnui_xqh414.dnuifood_16110100414.model.UserModel;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.Objects;
import java.util.regex.Pattern;

public class EditUserActivity extends BaseActivity implements OnRetrofitListener<UserInfo> {
    private TextInputLayout tl_username,tl_userpass,tl_Mobile,tl_address;
    private TextInputEditText tie_username,tie_userpass,tie_Mobile,tie_address;
    private MaterialButton button;
    private Toolbar toolbar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    void initViews() {
        setContentView(R.layout.activity_edit_user);

        tie_username = findViewById(R.id.tie_update_userName);
        tie_userpass = findViewById(R.id.tie_update_passWord);
        tie_Mobile = findViewById(R.id.tie_update_MobileNum);
        tie_address = findViewById(R.id.tie_update_address);

        tl_username = findViewById(R.id.tl_update_userName);
        tl_userpass = findViewById(R.id.tl_update_passWord);
        tl_Mobile = findViewById(R.id.tl_update_MobileNum);
        tl_address = findViewById(R.id.tl_update_address);

        button = findViewById(R.id.bt_update_confirm);

        toolbar = findViewById(R.id.toolBar_update);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
                default:
                    Toast.makeText(this, item.getItemId()+"", Toast.LENGTH_SHORT).show();
        }
        return true;
    }

    @Override
    void initEvents() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
//                if (tie_username.getText().toString().equals("")&&
//                        tie_userpass.getText().toString().equals("")&&
//                        tie_Moblie.getText().toString().equals("")&&
//                        tie_address.getText().toString().equals("")){
//                    Snackbar.make(v,"各项不能为空",Snackbar.LENGTH_SHORT).show();
//                }else
                    if (vailUsername(tie_username.getText().toString())
                        &&vailPassword(tie_userpass.getText().toString())
                        &&vailMobileNum(tie_Mobile.getText().toString())){
                        SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                    int userId = sharedPreferences.getInt("userid",-1);
                    UserModel model = new UserModel();
                    model.UpdateUser(userId, Objects.requireNonNull(tie_username.getText()).toString(),
                            Objects.requireNonNull(tie_userpass.getText()).toString(),
                            Objects.requireNonNull(tie_Mobile.getText()).toString(),
                            Objects.requireNonNull(tie_address.getText()).toString(), new OnRetrofitListener<ResultBean>() {
                                @SuppressLint("CommitPrefEdits")
                                @Override
                                public void onSuccess(ResultBean object, int flag) {
                                        if (object.getSuccess().equals("1")){
                                            Toast.makeText(EditUserActivity.this, "修改成功，请重新登录", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(EditUserActivity.this,LoginActivity.class)
                                                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                                            intent.putExtra("rg_password",tie_username.getText());
                                            intent.putExtra("rg_username","");
                                            finish();
                                            startActivity(intent);
                                        }else {
                                            Snackbar.make(v,"未知错误",Snackbar.LENGTH_SHORT).show();
                                        }
                                }

                                @Override
                                public void onFailure(String msg) {

                                }
                            });
                }
            }
        });
    }

    @Override
    void initData() {
        final SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userid",-1);
        UserModel model = new UserModel();
        model.getUser(userId,this);
    }

    private void showError(TextInputLayout layout, String error){
        layout.setError(error);
        Objects.requireNonNull(layout.getEditText()).setFocusable(true);
        layout.getEditText().setFocusableInTouchMode(true);
        layout.getEditText().requestFocus();
    }

    private boolean vailUsername(String userName){
        String p_username = "[a-zA-Z0-9_]{1,16}";

        if (userName.isEmpty()){
            showError(tl_username, "please input the username");
            return false;
        }
        if (!Pattern.matches(p_username,userName)){
            showError(tl_username, "username must use a-z, 0-9, underline and keep character in the 16");
            return false;
        }
        return true;
    }

    private boolean vailPassword(String password){
        String p_password = "[a-zA-Z0-9]{1,18}";

        if (password.isEmpty()){
            showError(tl_userpass, "please input the password");
            return false;
        }
        if(password.length()>18||password.length()<6){
            showError(tl_userpass, "password should between 18 and 6 characters");
            return false;
        }
        if (!Pattern.matches(p_password,password)){
            showError(tl_userpass, "password must use a-z, 0-9");
            return false;
        }
        return true;
    }

    private boolean vailMobileNum(String MobileNum){
        String p_num = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        if (MobileNum.isEmpty()){
            showError(tl_Mobile,"please input the Num");
            return false;
        }
        if (!Pattern.matches(p_num,MobileNum)){
            showError(tl_Mobile,"Please input correct Num");
            return false;
        }
        return true;
    }

    @Override
    public void onSuccess(UserInfo object, int flag) {
        tie_username.setText(object.getUsername());
        tie_address.setText(object.getAddress());
        tie_Mobile.setText(object.getMobilenum());
//        tie_userpass.setText(object.getUserpass());
    }

    @Override
    public void onFailure(String msg) {

    }
}
